package work.vcloud.baseinfo.controller;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.aspectj.weaver.ast.Var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import work.vcloud.frame.controller.BaseController;
import work.vcloud.frame.dao.OpenDao;
import work.vcloud.frame.vo.OutputVo;

@RestController
public class IPinfoController extends BaseController {
	@Autowired
	OpenDao openDao;

	@RequestMapping("user/getUserIP")
	public OutputVo getUserIP() {
		try {
			Map<String, Object> map = getParameterMap();
			map.remove("page");
			map.put("sqlMapId", "loginip.select");
			List<Map<String, Object>> ipList = openDao.queryForList(map);
			String ip = getIpAddress();
			String address = getAddressByIP(ip);
			Map<String, Object> ipMap = new HashMap<String, Object>();
			if (ipList.size() <= 0) {
				map.put("ip", ip);
				map.put("address", address);
				map.put("sqlMapId", "loginip.insert");
				openDao.insert(map);

				ipMap = map;
			} else {
				ipMap = ipList.get(0);
				if (!ipMap.get("ip").equals(ip)) {
					map.put("ip", ip);
					map.put("address", address);
					map.put("sqlMapId", "loginip.insert");
					openDao.insert(map);

					map = null;
					map.put("sqlMapId", "loginip.select");
					ipMap = openDao.queryForList(map).get(1);
				}
			}
			return output(ipMap);
		} catch (Exception e) {
			e.printStackTrace();
			return output("9999");
		}
	}

	/**
	 * 获取本机的外网ip地址
	 * 
	 * @return
	 */
	public String getIpAddress() {
		String ip = request.getHeader("X-Forwarded-For");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_CLIENT_IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}

	public static String getAddressByIP(String strIP) {
		try {
			URL url = new URL("http://opendata.baidu.com/api.php?query="+strIP+"&co=&resource_id=6006&t=1433920989928&ie=utf8&oe=utf-8&format=json");
			URLConnection conn = url.openConnection();
			BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
			String line = null;
			StringBuffer result = new StringBuffer();
			while ((line = reader.readLine()) != null) {
				result.append(line);
			}
		   reader.close();
		   String ipAddr = result.toString();
		   try {
			   JSONObject obj = (JSONObject) JSON.parse(ipAddr);
			   if("0".equals(obj.get("status").toString())){
				   JSONArray arr = (JSONArray) JSON.parseArray(obj.get("data").toString());
				   if(arr.size() > 0){
					   JSONObject obj3 = arr.getJSONObject(0);

					   return obj3.get("location").toString();
				   }else{
					   return "读取失败";
				   }

			   }else{
				   return "读取失败";
			   }
		   	} catch (Exception e) {
		   		e.printStackTrace();
		   		return "读取失败";
		   }
		} catch (Exception e) {
		   return "读取失败";
		}
	}
}